<?php
declare (strict_types = 1);

namespace app\api\controller;

use TencentCloud\Common\Credential;
use TencentCloud\Common\Profile\ClientProfile;
use TencentCloud\Common\Profile\HttpProfile;
use TencentCloud\Common\Exception\TencentCloudSDKException;
use TencentCloud\Live\V20180801\LiveClient;
use TencentCloud\Live\V20180801\Models\DescribeLiveStreamStateRequest;
use think\Request;

class TencentLive
{
    function getPushUrl($domain = null, $streamName = null, $key = null, $time = null){
        $domain = config('tencent.live.push');
        $streamName = config('tencent.live.streamName');
        $key = config('tencent.live.key');
        $time = config('tencent.live.time');
        if($key && $time){
            $txTime = strtoupper(base_convert(strtotime($time),10,16));
            $txSecret = md5($key.$streamName.$txTime);
            $ext_str = "?".http_build_query(array(
                    "txSecret"=> $txSecret,
                    "txTime"=> $txTime
                ));
        }
        $pushUrl = "rtmp://".$domain."/live/".$streamName . (isset($ext_str) ? $ext_str : "");
        return json(['code'=>10001,'msg'=>'推流地址生成成功','data'=>['pushUrl'=>$pushUrl]]);
    }

    function getPullUrl($domain = null, $streamName = null)
    {
        $domain = config('tencent.live.pull');
        $streamName = config('tencent.live.streamName');
        $pullUrl = "http://".$domain."/live/".$streamName.".m3u8";
        return json(['code'=>10001,'msg'=>'播放地址获取成功','data'=>['pullUrl'=>$pullUrl]]);
    }

    public function getLiveStatus()
    {
        try {
            $cred = new Credential("AKID4wZv0oLcbJkvqTpvkIZZKo1wbz6wWopZ", "UhcGdjY6NO8alfIdhU0FCsIQHrACxSge");
            $httpProfile = new HttpProfile();
            $httpProfile->setEndpoint("live.tencentcloudapi.com");

            $clientProfile = new ClientProfile();
            $clientProfile->setHttpProfile($httpProfile);
            $client = new LiveClient($cred, "", $clientProfile);

            $req = new DescribeLiveStreamStateRequest();

            $params = array(
                "AppName" => "live",
                "DomainName" => "push.lbynice.com",
                "StreamName" => "1902A"
            );
            $req->fromJsonString(json_encode($params));

            $resp = $client->DescribeLiveStreamState($req);

            $liveStatus = json_decode($resp->toJsonString());
            if ($liveStatus->StreamState === 'inactive'){
                return json(['code'=>10002,'msg'=>'直播已结束','data'=>[]]);
            }
            if ($liveStatus->StreamState === 'active'){
                return json(['code'=>10001,'msg'=>'正在直播','data'=>[]]);
            }
        }
        catch(TencentCloudSDKException $e) {
            return json(['code'=>10004,'msg'=>'直播异常','data'=>[]]);
        }
    }
}
